import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { getGoodsApi } from '../../services/axios'

export interface GoodsList {
    name:string
    description:string
    sellCount:number
    rating:number
    price:number
    image:string
    count?:number
}

export interface Goods {
    name:string
    foods:GoodsList[]
}

export interface initialState {
    goodsList:Goods[],
    cardList:GoodsList[]
} 

const initialState:initialState = {
    goodsList:[],
    cardList:[]
}



export const getGoods = createAsyncThunk('goods/getGoods',async () => {
    const res = await getGoodsApi()
    return res.data.data
})

const goodsSlice = createSlice({
    name:'goods',
    initialState,
    reducers:{
        changeCardList(state,action){
            const index = state.cardList.findIndex(v => v.name === action.payload.name)
            if(index === -1){
                state.cardList.push({...action.payload,count:1})
            }else {
                state.cardList[index].count = state.cardList[index].count! + 1
            }
        },
        delCount(state,action){
            const index = state.cardList.findIndex(v => v.name === action.payload.name)
            if(state.cardList[index].count! > 1) {
                state.cardList[index].count = state.cardList[index].count! - 1
            }else{
                state.cardList.splice(index,1)
            }
        }
    },
                        
    extraReducers:builder => {
        builder
            .addCase(getGoods.fulfilled,(state,action)=>{
                console.log(action.payload)
                state.goodsList = action.payload
            })    
    }

})


export const {changeCardList,delCount} = goodsSlice.actions

export default goodsSlice.reducer

